package com.lcicl.reggie.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lcicl.reggie.common.R;
import com.lcicl.reggie.entity.Employee;
import com.lcicl.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/*
  Date: 2023/07/23
  Author: Luochao
  Description:
*/
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     *
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {

        //将密码进行md5加密
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //查询用户是否存在
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(queryWrapper);

        //没查到返回错误
        if (emp == null) {
            return R.error("没有该用户，登录失败");
        }

        //查询密码
        if (!emp.getPassword().equals(password)) {
            return R.error("密码错误");
        }

        //查看用户是否禁用
        if (emp.getStatus() == 0) {
            return R.error("账号已禁用");
        }

        //登录成功，将用户ID放入Session
        request.getSession().setAttribute("employee", emp.getId());

        return R.success(emp);
    }

    /**
     * 员工退出
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("employee");


        return R.success("退出成功");
    }

    /**
     * 新增员工
     *
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody Employee employee) {
        log.info("员工信息：{}", JSON.toJSONString(employee));

        //取身份证后六位作为登录密码
        String password = employee.getIdNumber().substring(12);
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        employee.setPassword(password);

//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());

//        long empId = (long) request.getSession().getAttribute("employee");
//        employee.setCreateUser(empId);
//        employee.setUpdateUser(empId);

//        try {
        employeeService.save(employee);
//        } catch (Exception e) {
//            return R.error("添加员工失败");
//        }

        return R.success("新增员工成功");
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        log.info("page={},pageSize={},name={}", page, pageSize, name);

        //创建Page类，使用MP查询
        Page<Employee> pageInfo = new Page(page, pageSize);


        //查询条件
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper();
        //如果name不为空添加
        queryWrapper.like(StringUtils.isNotEmpty(name), Employee::getName, name)
                .or().like(StringUtils.isNotEmpty(name), Employee::getUsername, name)
                .or().like(StringUtils.isNotEmpty(name), Employee::getPhone, name);
        //排序条件
        queryWrapper.orderByDesc(Employee::getUpdateTime);

        Page<Employee> rePage = employeeService.page(pageInfo, queryWrapper);


        //将密码置空
        List<Employee> records = rePage.getRecords();
        for (Employee employee : records) {
            employee.setPassword("");
        }
        rePage.setRecords(records);


        return R.success(rePage);
    }

    /**
     * 修改员工状态
     *
     * @param request
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> update(HttpServletRequest request, @RequestBody Employee employee) {

//        long empId = (long) request.getSession().getAttribute("employee");
//        employee.setUpdateUser(empId);
//        log.info("employee:{}", JSON.toJSONString(employee));

        boolean b = employeeService.updateById(employee);

//        log.info("{}", b);

        return R.success("修改成功");
    }

    /**
     * 查询用户
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> selectEmployee(@PathVariable long id) {
        log.info("修改id:{}", id);
        Employee employee = employeeService.getById(id);
        log.info("查询出的employee为：{}",employee);

        if (employee == null) {
            return R.error("没有查询到对应员工信息");
        }

        //密码置空，保证安全
        employee.setPassword("");

        return R.success(employee);
    }




}
